/**
 * 自定义函数解析器 v0.1
 * @param {string} str 
 * @returns 
 */
export default function parser(str) {

    if(!str.includes('x')) {
        throw new SyntaxError('必须包含自变量x');
    }
    console.log(str);
    const keyList = keywordAnalysis(Array.from(str));
    str = toJs(keyList);
    console.log('JS:',str)
    return new Function('x', `return ${str}`)
}

/**
 * 符号分析器
 * @param {string[]} arr 
 * @returns 
 */
export function keywordAnalysis (arr) {
    let pos = 0;
    let pattern = 0; // 0 标识符 1符号
    let currentKey = ''
    const rel = [];
    // 目前没有复杂的语法 ，这样足够了
    arr.forEach(v=> {
        if(/[A-z]/.test(v)) {
            currentKey= currentKey+v;
        } else {
            if (currentKey) {
                rel.push(currentKey);
                currentKey ='';
            }
            rel.push(v);
        }
    })
    if (currentKey) {
        rel.push(currentKey);
    }
    return rel
}
/**
 * 关键字转换
 * @param {string} key 
 * @returns 
 */
export function keyTransform(key){
    const keyMap = {
        cos: 'Math.cos',
        tan: 'Math.tan',
        sin: 'Math.sin',
        cot: 'Math.cot',
        abs: 'Math.abs',
    }
    const rel = keyMap[key];
    if(!rel) {
        throw new SyntaxError('不支持的函数名:'+key)
    }
    return rel;
}
/**
 * 将关键字数组转换为JS语句
 * @param {string[]} arr 
 */
export function toJs(arr) {
    let i = 0;
    let rel = ''
    while(i<arr.length) {
        const key = arr[i];
        console.log(`now key:${key},chars: ${key.length}`)
        if (key.length> 1) {
            const newKey = keyTransform(key);
            rel = rel+newKey;
        } else {
            rel = rel + key;
        }
        i++;
    }
    return rel;
}